package com.dhl.fin.api.service;

import cn.hutool.cron.CronUtil;
import com.dhl.fin.api.domain.ExtraJobCron;
import com.dhl.fin.api.domain.RemindTask;
import com.dhl.fin.api.util.CronJobUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.function.Consumer;

/**
 * @author CuiJianbo
 * @since 2025/5/8
 */
@Slf4j
@Service
public class SystemInitEnvService implements ApplicationListener<ApplicationReadyEvent> {

    @Autowired
    private RemindTaskService remindTaskService;

    @Autowired
    private ExtraJobCronService extraJobCronService;

    @Autowired
    private CronJobService cronJobService;

    @Override
    public void onApplicationEvent(ApplicationReadyEvent event) {

        try {
            List<ExtraJobCron> extraJobCrons = extraJobCronService.getAllExtraJobCron();
            for (ExtraJobCron extraJobCron : extraJobCrons) {
                //注册定时任务
                String scheduleId = cronJobService.addCronJob(extraJobCron.getCron(), extraJobCron.getRemindTask(), extraJobCron);
                extraJobCronService.updateFieldById(extraJobCron.getId(), "scheduleIdNum", scheduleId);
            }
            log.info("所有定时任务注册成功。");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        CronUtil.start();

    }

}